<template>
  <div class="trace-detail">
    <div class="page-header">
      <div class="header-left">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <h2>溯源详情</h2>
        <p>溯源记录ID: {{ traceId }}</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="printDetail">
          <el-icon><Printer /></el-icon>
          打印
        </el-button>
        <el-button type="success" @click="exportDetail">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </div>
    </div>

    <div class="detail-content" v-loading="loading">
      <!-- 基本信息卡片 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <label>商品名称：</label>
              <span>{{ traceInfo.productName }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>商品编码：</label>
              <span>{{ traceInfo.productCode }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>生产批次：</label>
              <span>{{ traceInfo.batchNumber }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <label>供应商：</label>
              <span>{{ traceInfo.supplierName }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>生产日期：</label>
              <span>{{ traceInfo.productionDate }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>保质期：</label>
              <span>{{ traceInfo.expiryDate }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="info-item">
              <label>溯源状态：</label>
              <el-tag :type="getStatusType(traceInfo.status)">
                {{ getStatusText(traceInfo.status) }}
              </el-tag>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>完整度：</label>
              <el-progress
                :percentage="traceInfo.completeness"
                :color="getCompletenessColor(traceInfo.completeness)"
                :stroke-width="8"
                style="width: 120px"
              />
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>创建时间：</label>
              <span>{{ traceInfo.createTime }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 溯源链路图 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <span>溯源链路图</span>
            <el-button type="primary" size="small" @click="refreshTraceChain">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </template>
        
        <div class="trace-chain">
          <div class="chain-container">
            <div
              v-for="(node, index) in traceChain"
              :key="index"
              class="chain-node"
              :class="{ active: node.status === 'completed', pending: node.status === 'pending' }"
            >
              <div class="node-icon">
                <el-icon v-if="node.status === 'completed'"><Check /></el-icon>
                <el-icon v-else-if="node.status === 'pending'"><Clock /></el-icon>
                <el-icon v-else><Warning /></el-icon>
              </div>
              <div class="node-content">
                <h4>{{ node.title }}</h4>
                <p>{{ node.description }}</p>
                <div class="node-details">
                  <el-tag v-for="detail in node.details" :key="detail.key" size="small">
                    {{ detail.key }}: {{ detail.value }}
                  </el-tag>
                </div>
              </div>
              <div class="node-time">{{ node.time }}</div>
            </div>
            
            <!-- 连接线 -->
            <div class="chain-lines">
              <div
                v-for="index in traceChain.length - 1"
                :key="index"
                class="chain-line"
                :class="{ active: traceChain[index - 1].status === 'completed' }"
              ></div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 详细溯源信息 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <span>详细溯源信息</span>
          </div>
        </template>
        
        <el-tabs v-model="activeTab" type="border-card">
          <el-tab-pane label="生产环节" name="production">
            <div class="tab-content">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="生产厂家">{{ productionInfo.manufacturer }}</el-descriptions-item>
                <el-descriptions-item label="生产许可证">{{ productionInfo.license }}</el-descriptions-item>
                <el-descriptions-item label="生产地址">{{ productionInfo.address }}</el-descriptions-item>
                <el-descriptions-item label="生产数量">{{ productionInfo.quantity }}</el-descriptions-item>
                <el-descriptions-item label="生产设备">{{ productionInfo.equipment }}</el-descriptions-item>
                <el-descriptions-item label="质检员">{{ productionInfo.inspector }}</el-descriptions-item>
                <el-descriptions-item label="生产环境">{{ productionInfo.environment }}</el-descriptions-item>
                <el-descriptions-item label="生产标准">{{ productionInfo.standard }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="检测环节" name="inspection">
            <div class="tab-content">
              <el-table :data="inspectionRecords" style="width: 100%" border>
                <el-table-column prop="testDate" label="检测日期" width="120" />
                <el-table-column prop="testType" label="检测类型" width="120" />
                <el-table-column prop="testResult" label="检测结果" width="100">
                  <template #default="{ row }">
                    <el-tag :type="row.testResult === '合格' ? 'success' : 'danger'">
                      {{ row.testResult }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="testValue" label="检测值" width="100" />
                <el-table-column prop="standard" label="标准值" width="100" />
                <el-table-column prop="inspector" label="检测员" width="100" />
                <el-table-column prop="remarks" label="备注" show-overflow-tooltip />
              </el-table>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="运输环节" name="transport">
            <div class="tab-content">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="运输公司">{{ transportInfo.company }}</el-descriptions-item>
                <el-descriptions-item label="车牌号">{{ transportInfo.vehicleNumber }}</el-descriptions-item>
                <el-descriptions-item label="司机姓名">{{ transportInfo.driver }}</el-descriptions-item>
                <el-descriptions-item label="联系电话">{{ transportInfo.phone }}</el-descriptions-item>
                <el-descriptions-item label="出发时间">{{ transportInfo.departureTime }}</el-descriptions-item>
                <el-descriptions-item label="到达时间">{{ transportInfo.arrivalTime }}</el-descriptions-item>
                <el-descriptions-item label="运输温度">{{ transportInfo.temperature }}</el-descriptions-item>
                <el-descriptions-item label="运输距离">{{ transportInfo.distance }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="仓储环节" name="storage">
            <div class="tab-content">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="仓库名称">{{ storageInfo.warehouse }}</el-descriptions-item>
                <el-descriptions-item label="库位编号">{{ storageInfo.location }}</el-descriptions-item>
                <el-descriptions-item label="入库时间">{{ storageInfo.inTime }}</el-descriptions-item>
                <el-descriptions-item label="出库时间">{{ storageInfo.outTime }}</el-descriptions-item>
                <el-descriptions-item label="存储温度">{{ storageInfo.temperature }}</el-descriptions-item>
                <el-descriptions-item label="存储湿度">{{ storageInfo.humidity }}</el-descriptions-item>
                <el-descriptions-item label="保管员">{{ storageInfo.keeper }}</el-descriptions-item>
                <el-descriptions-item label="存储条件">{{ storageInfo.condition }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>

      <!-- 质量检测报告 -->
      <el-card class="detail-card">
        <template #header>
          <div class="card-header">
            <span>质量检测报告</span>
          </div>
        </template>
        
        <div class="quality-report">
          <div class="report-summary">
            <el-row :gutter="20">
              <el-col :span="6">
                <div class="summary-item">
                  <div class="summary-label">检测项目</div>
                  <div class="summary-value">{{ qualityReport.totalTests }}</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="summary-item">
                  <div class="summary-label">合格项目</div>
                  <div class="summary-value success">{{ qualityReport.passedTests }}</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="summary-item">
                  <div class="summary-label">不合格项目</div>
                  <div class="summary-value danger">{{ qualityReport.failedTests }}</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="summary-item">
                  <div class="summary-label">合格率</div>
                  <div class="summary-value">{{ qualityReport.passRate }}%</div>
                </div>
              </el-col>
            </el-row>
          </div>
          
          <el-table :data="qualityReport.details" style="width: 100%" border>
            <el-table-column prop="testItem" label="检测项目" width="150" />
            <el-table-column prop="testMethod" label="检测方法" width="150" />
            <el-table-column prop="testResult" label="检测结果" width="100">
              <template #default="{ row }">
                <el-tag :type="row.testResult === '合格' ? 'success' : 'danger'">
                  {{ row.testResult }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="testValue" label="检测值" width="100" />
            <el-table-column prop="standard" label="标准值" width="100" />
            <el-table-column prop="unit" label="单位" width="80" />
            <el-table-column prop="conclusion" label="结论" show-overflow-tooltip />
          </el-table>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Printer, Download, Refresh, Check, Clock, Warning } from '@element-plus/icons-vue'

export default defineComponent({
  name: 'TraceDetail',
  components: {
    ArrowLeft,
    Printer,
    Download,
    Refresh,
    Check,
    Clock,
    Warning
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const loading = ref(false)
    const activeTab = ref('production')
    
    // 溯源ID
    const traceId = computed(() => route.params.id || 'TR001')
    
    // 溯源基本信息
    const traceInfo = reactive({
      productName: '有机苹果',
      productCode: 'P001',
      batchNumber: '20240115-001',
      supplierName: '绿色农场供应商',
      productionDate: '2024-01-15',
      expiryDate: '2024-02-15',
      status: 'complete',
      completeness: 95,
      createTime: '2024-01-15 10:30:00'
    })
    
    // 溯源链路
    const traceChain = ref([
      {
        title: '种植环节',
        description: '有机苹果种植，无农药使用',
        status: 'completed',
        time: '2024-01-10 08:00:00',
        details: [
          { key: '种植基地', value: '绿色农场A区' },
          { key: '种植面积', value: '50亩' },
          { key: '种植方式', value: '有机种植' }
        ]
      },
      {
        title: '收获环节',
        description: '人工采摘，品质筛选',
        status: 'completed',
        time: '2024-01-14 14:30:00',
        details: [
          { key: '收获数量', value: '5000kg' },
          { key: '筛选标准', value: '一级果' },
          { key: '包装规格', value: '500g/袋' }
        ]
      },
      {
        title: '生产加工',
        description: '清洗、分级、包装',
        status: 'completed',
        time: '2024-01-15 09:00:00',
        details: [
          { key: '加工设备', value: '自动化生产线' },
          { key: '生产数量', value: '10000袋' },
          { key: '质检员', value: '李四' }
        ]
      },
      {
        title: '质量检测',
        description: '农药残留、重金属检测',
        status: 'completed',
        time: '2024-01-15 11:00:00',
        details: [
          { key: '检测项目', value: '农药残留、重金属' },
          { key: '检测结果', value: '合格' },
          { key: '检测员', value: '王五' }
        ]
      },
      {
        title: '运输配送',
        description: '冷藏车运输，温度控制',
        status: 'completed',
        time: '2024-01-15 16:00:00',
        details: [
          { key: '运输方式', value: '冷藏车' },
          { key: '运输温度', value: '2-8℃' },
          { key: '司机', value: '张三' }
        ]
      },
      {
        title: '超市上架',
        description: '商品上架销售',
        status: 'completed',
        time: '2024-01-15 18:00:00',
        details: [
          { key: '上架位置', value: 'A区货架' },
          { key: '上架数量', value: '1000袋' },
          { key: '操作员', value: '赵六' }
        ]
      }
    ])
    
    // 生产环节信息
    const productionInfo = reactive({
      manufacturer: '绿色农场食品有限公司',
      license: 'SC101234567890',
      address: '北京市朝阳区绿色农业园区A区1号',
      quantity: '10000袋',
      equipment: '自动化清洗分级包装线',
      inspector: '李四',
      environment: 'GMP标准生产车间',
      standard: 'GB/T 19630有机产品标准'
    })
    
    // 检测记录
    const inspectionRecords = ref([
      {
        testDate: '2024-01-15',
        testType: '农药残留',
        testResult: '合格',
        testValue: '未检出',
        standard: '≤0.01mg/kg',
        inspector: '王五',
        remarks: '检测结果符合国家标准'
      },
      {
        testDate: '2024-01-15',
        testType: '重金属',
        testResult: '合格',
        testValue: '0.005mg/kg',
        standard: '≤0.1mg/kg',
        inspector: '王五',
        remarks: '铅含量检测合格'
      },
      {
        testDate: '2024-01-15',
        testType: '外观检查',
        testResult: '合格',
        testValue: '良好',
        standard: '无破损、无腐烂',
        inspector: '李四',
        remarks: '外观完整，品质良好'
      }
    ])
    
    // 运输信息
    const transportInfo = reactive({
      company: '绿色物流有限公司',
      vehicleNumber: '京A12345',
      driver: '张三',
      phone: '13800138000',
      departureTime: '2024-01-15 16:00:00',
      arrivalTime: '2024-01-15 18:00:00',
      temperature: '2-8℃',
      distance: '50公里'
    })
    
    // 仓储信息
    const storageInfo = reactive({
      warehouse: '绿色超市配送中心',
      location: 'A-01-01',
      inTime: '2024-01-15 18:00:00',
      outTime: '2024-01-16 08:00:00',
      temperature: '2-8℃',
      humidity: '60-70%',
      keeper: '赵六',
      condition: '冷藏存储'
    })
    
    // 质量检测报告
    const qualityReport = reactive({
      totalTests: 8,
      passedTests: 8,
      failedTests: 0,
      passRate: 100,
      details: [
        {
          testItem: '农药残留',
          testMethod: 'GB/T 5009.199',
          testResult: '合格',
          testValue: '未检出',
          standard: '≤0.01mg/kg',
          unit: 'mg/kg',
          conclusion: '农药残留检测合格'
        },
        {
          testItem: '铅',
          testMethod: 'GB 5009.12',
          testResult: '合格',
          testValue: '0.005',
          standard: '≤0.1',
          unit: 'mg/kg',
          conclusion: '铅含量检测合格'
        },
        {
          testItem: '汞',
          testMethod: 'GB 5009.17',
          testResult: '合格',
          testValue: '0.002',
          standard: '≤0.01',
          unit: 'mg/kg',
          conclusion: '汞含量检测合格'
        },
        {
          testItem: '砷',
          testMethod: 'GB 5009.11',
          testResult: '合格',
          testValue: '0.008',
          standard: '≤0.5',
          unit: 'mg/kg',
          conclusion: '砷含量检测合格'
        },
        {
          testItem: '镉',
          testMethod: 'GB 5009.15',
          testResult: '合格',
          testValue: '0.003',
          standard: '≤0.05',
          unit: 'mg/kg',
          conclusion: '镉含量检测合格'
        },
        {
          testItem: '外观',
          testMethod: '目视检查',
          testResult: '合格',
          testValue: '良好',
          standard: '无破损、无腐烂',
          unit: '-',
          conclusion: '外观完整，品质良好'
        },
        {
          testItem: '大小规格',
          testMethod: '称重测量',
          testResult: '合格',
          testValue: '500±10g',
          standard: '500±20g',
          unit: 'g',
          conclusion: '规格符合要求'
        },
        {
          testItem: '包装完整性',
          testMethod: '目视检查',
          testResult: '合格',
          testValue: '完整',
          standard: '无破损、无漏气',
          unit: '-',
          conclusion: '包装完整，密封良好'
        }
      ]
    })
    
    // 加载溯源详情
    const loadTraceDetail = async () => {
      loading.value = true
      try {
        // 模拟API请求
        await new Promise(resolve => setTimeout(resolve, 1000))
        // 这里应该调用API获取溯源详情
      } catch (error) {
        console.error('加载溯源详情失败:', error)
        ElMessage.error('加载溯源详情失败')
      } finally {
                  loading.value = true
      }
    }
    
    // 返回上一页
    const goBack = () => {
      router.go(-1)
    }
    
    // 打印详情
    const printDetail = () => {
      window.print()
    }
    
    // 导出详情
    const exportDetail = () => {
      ElMessage.success('溯源详情导出成功')
    }
    
    // 刷新溯源链路
    const refreshTraceChain = () => {
      ElMessage.success('溯源链路已刷新')
    }
    
    // 获取状态类型
    const getStatusType = (status) => {
      const statusMap = {
        'complete': 'success',
        'incomplete': 'warning',
        'abnormal': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'complete': '完整',
        'incomplete': '不完整',
        'abnormal': '异常'
      }
      return statusMap[status] || '未知'
    }
    
    // 获取完整度颜色
    const getCompletenessColor = (completeness) => {
      if (completeness >= 90) return '#67C23A'
      if (completeness >= 70) return '#E6A23C'
      return '#F56C6C'
    }
    
    onMounted(() => {
      loadTraceDetail()
    })
    
    return {
      loading,
      activeTab,
      traceId,
      traceInfo,
      traceChain,
      productionInfo,
      inspectionRecords,
      transportInfo,
      storageInfo,
      qualityReport,
      loadTraceDetail,
      goBack,
      printDetail,
      exportDetail,
      refreshTraceChain,
      getStatusType,
      getStatusText,
      getCompletenessColor
    }
  }
})
</script>

<style scoped>
.trace-detail {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-left h2 {
  margin: 0 0 5px 0;
  color: #2563eb;
}

.header-left p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.info-item label {
  font-weight: bold;
  color: #666;
  min-width: 100px;
  margin-right: 10px;
}

.trace-chain {
  padding: 20px 0;
}

.chain-container {
  position: relative;
  padding: 20px 0;
}

.chain-node {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 2px solid #e1e5e9;
  transition: all 0.3s ease;
}

.chain-node.active {
  border-color: #67C23A;
  background: #f0f9ff;
}

.chain-node.pending {
  border-color: #E6A23C;
  background: #fef7e0;
}

.node-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: #e1e5e9;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 20px;
  color: #666;
}

.chain-node.active .node-icon {
  background: #67C23A;
  color: white;
}

.chain-node.pending .node-icon {
  background: #E6A23C;
  color: white;
}

.node-content {
  flex: 1;
}

.node-content h4 {
  margin: 0 0 5px 0;
  color: #2563eb;
}

.node-content p {
  margin: 0 0 10px 0;
  color: #666;
}

.node-details {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.node-time {
  color: #999;
  font-size: 12px;
  min-width: 120px;
  text-align: right;
}

.chain-lines {
  position: absolute;
  left: 45px;
  top: 70px;
  bottom: 70px;
  width: 2px;
  background: #e1e5e9;
}

.chain-line {
  height: 30px;
  background: #e1e5e9;
  margin-bottom: 30px;
}

.chain-line.active {
  background: #67C23A;
}

.tab-content {
  padding: 20px 0;
}

.quality-report {
  padding: 20px 0;
}

.report-summary {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.summary-item {
  text-align: center;
}

.summary-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.summary-value {
  font-size: 24px;
  font-weight: bold;
  color: #2563eb;
}

.summary-value.success {
  color: #67C23A;
}

.summary-value.danger {
  color: #F56C6C;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .header-right {
    width: 100%;
    display: flex;
    gap: 10px;
  }
  
  .chain-node {
    flex-direction: column;
    text-align: center;
  }
  
  .node-icon {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .node-time {
    text-align: center;
    margin-top: 10px;
  }
}
</style> 